import { cadAppLog, CMEVENTS } from '@amcax/base';
import { dataManager, docMgr, userEvents } from '@app-cad/module';
import { KeyboardArrowDown } from '@mui/icons-material';
import {
  alpha,
  Button,
  Menu,
  MenuItem,
  MenuProps,
  styled,
} from '@mui/material';
import React, { useEffect } from 'react';
import { BsBalloon, BsBalloonFill } from 'react-icons/bs';
import { materialSetter } from './MaterialSetter';
import { MaterialParams } from './types';

const StyledMenu = styled((props: MenuProps) => (
  <Menu
    elevation={0}
    anchorOrigin={{
      vertical: 'bottom',
      horizontal: 'right',
    }}
    transformOrigin={{
      vertical: 'top',
      horizontal: 'right',
    }}
    {...props}
  />
))(({ theme }) => ({
  '& .MuiPaper-root': {
    borderRadius: 6,
    marginTop: theme.spacing(1),
    minWidth: 180,
    color:
      theme.palette.mode === 'light'
        ? 'rgb(55, 65, 81)'
        : theme.palette.grey[300],
    boxShadow:
      'rgb(255, 255, 255) 0px 0px 0px 0px, rgba(0, 0, 0, 0.05) 0px 0px 0px 1px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.05) 0px 4px 6px -2px',
    '& .MuiMenu-list': {
      padding: '4px 0',
    },
    '& .MuiMenuItem-root': {
      '& .MuiSvgIcon-root': {
        fontSize: 18,
        color: theme.palette.text.secondary,
        marginRight: theme.spacing(1.5),
      },
      '&:active': {
        backgroundColor: alpha(
          theme.palette.primary.main,
          theme.palette.action.selectedOpacity,
        ),
      },
    },
  },
}));

export default function MaterialLibs({
  dxid,
  materials,
  faceIndex,
}: MaterialParams) {
  const [_materials, setMaterials] = React.useState([]);
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const dxidRef = React.useRef(null);
  const faceIndexRef = React.useRef(null);
  const open = Boolean(anchorEl);
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  useEffect(() => {
    cadAppLog('MaterialLibs useEffect', dxid, materials, faceIndex);
    dxidRef.current = dxid;
    faceIndexRef.current = faceIndex;
    registerEvents();
    loadMaterials();
  }, []);
  const registerEvents = () => {
    userEvents.on(CMEVENTS.MATERIAL_ADDED, async (material: any) => {
      cadAppLog('MaterialLibs on MATERIAL_ADDED', material);
      loadMaterials();
    });
  };
  const loadMaterials = async () => {
    await docMgr.updateDocumentMaterials();
    const materials = dataManager.getAllMaterials();
    setMaterials(materials);
  };

  const selectMaterial = async (material: any) => {
    const dxid = dxidRef.current;
    const faceIndex = faceIndexRef.current;
    if (dxid) {
      materialSetter.setMaterial(dxid, faceIndex, material.id);
      // await wsApi.setMaterials(dxid, faceIndex, material.id)
      material['dxid'] = dxid;
      material['faceIndex'] = faceIndex;
      userEvents.emit(CMEVENTS.MATERIAL_ADDED, material);
    }
    handleClose();
  };

  return (
    <>
      <Button
        id='demo-customized-button'
        size='small'
        sx={{
          '.MuiButton-startIcon': {
            marginRight: '0px',
          },
        }}
        aria-controls={open ? 'demo-customized-menu' : undefined}
        aria-haspopup='true'
        aria-expanded={open ? 'true' : undefined}
        variant='contained'
        disableElevation
        onClick={handleClick}
        startIcon={<BsBalloon />}
        endIcon={<KeyboardArrowDown />}>
        材质库
      </Button>
      <StyledMenu
        id='demo-customized-menu'
        MenuListProps={{
          'aria-labelledby': 'demo-customized-button',
        }}
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}>
        {_materials.length > 0 ? (
          _materials.map((material, index) => {
            return (
              <MenuItem
                key={index}
                onClick={() => {
                  selectMaterial(material);
                }}
                disableRipple>
                {material.color === '' ? (
                  <BsBalloon />
                ) : (
                  <BsBalloonFill color={material.color} />
                )}
                {material.name}
              </MenuItem>
            );
          })
        ) : (
          <div></div>
        )}
      </StyledMenu>
    </>
  );
}
